package com.anji.plus.gaea.job.trigger.scheduler;

import com.anji.plus.gaea.job.trigger.config.TriggerConfiguration;
import com.anji.plus.gaea.job.trigger.thread.JobCompleteHelper;
import com.anji.plus.gaea.job.trigger.thread.JobRegistryHelper;
import com.anji.plus.gaea.job.trigger.thread.JobScheduleHelper;
import com.anji.plus.gaea.job.trigger.thread.JobTriggerPoolHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by xuxueli on 17/3/10.
 *
 * Borrowed from xxljob v2.4.0
 */
public class XxlJobScheduler {

    private static final Logger logger = LoggerFactory.getLogger(XxlJobScheduler.class);

    public void start() throws Exception {
        // 初始化触发线程池，有快慢线程池
        JobTriggerPoolHelper.toStart();

        // 30秒执行一次，将90秒没有续约的执行器删除，并初始化服务注册删除线程池
        JobRegistryHelper.getInstance().start();

        // todo
        // 调度日志失败重新调度，日志失败告警
        //JobFailMonitorHelper.getInstance().start();

        // 将丢失主机调度日志重置为失败
        JobCompleteHelper.getInstance().start();

        // 调度器执行任务
        // 调度线程50秒执行一次，查询5秒内执行任务，并按不同逻辑执行
        // 时间轮线程每1秒执行一次，时间轮算法，并向前跨一个时刻
        JobScheduleHelper.getInstance().start();

        logger.info("初始化 gaea-job 调度器完成");
    }

    public void stop() throws Exception {
        JobScheduleHelper.getInstance().toStop();
        JobCompleteHelper.getInstance().toStop();
        JobRegistryHelper.getInstance().stop();
        JobTriggerPoolHelper.toStop();
    }

    // ---------------------- executor-client ----------------------
    private static ConcurrentHashMap<String, ExecutorClient> executorClientConcurrentHashMap = new ConcurrentHashMap<String, ExecutorClient>();
    public static ExecutorClient getExecutorClient(String address) throws Exception{
        // valid
        if (address==null || address.trim().length()==0) {
            return null;
        }

        // load-cache
        address = address.trim();
        ExecutorClient executorBiz = executorClientConcurrentHashMap.get(address);
        if (executorBiz != null) {
            return executorBiz;
        }

        String accessToken = TriggerConfiguration.getInstance().getTriggerProperties().getAccessToken();
        // set-cache
        executorBiz = new ExecutorClient(address, accessToken);

        executorClientConcurrentHashMap.put(address, executorBiz);
        return executorBiz;
    }
}
